import 'ol/ol.css';
import Map from 'ol/Map';
import View from 'ol/View'
import { unByKey } from 'ol/Observable';
import Overlay from 'ol/Overlay';
import Draw from 'ol/interaction/Draw';
import { Tile as TileLayer, Vector as VectorLayer } from 'ol/layer';
import { OSM, Vector as VectorSource } from 'ol/source';
import { Style, Circle as CircleStyle, Stroke, Fill } from 'ol/style';
import { LineString, Polygon } from 'ol/geom';
import { getArea, getLength } from 'ol/sphere';
import { fromLonLat } from 'ol/proj';

const raster = new TileLayer({
    source: new OSM()
});

const source = new VectorSource();

const vector = new VectorLayer({
    source: source,
    style: new Style({
        fill: new Fill({
            color: 'rgba(255,255,255,0.2)'
        }),
        stroke: new Stroke({
            color: '#ffcc33',
            width: 2
        }),
        image: new CircleStyle({
            radius: 7,
            fill: new Fill({
                color: 'red'
            })
        })
    })
})

let sketch; // 当前画的图形
let helpTooltipElement, helpTooltip, measureTooltipElement, measureTooltip;
const continuePolyginMsg = '点击继续画图形',
    continueLineMsg = '点击继续画直线';

let draw; // global so we can remove it later
const typeSleect = document.getElementById('type');

const addInteraction = function() {
    const type = (typeSleect.value == 'area' ? 'Polygon' : 'LineString');
    draw = new Draw({
        source: source,
        tpye: type,
        style: new Style({
            fill: new Fill({
                color: 'rgba(255, 255, 255, 0.2)'
            }),
            stroke: new Stroke({
                color: 'rgba(0, 0, 0, 0.5)'
            }),
            image: new CircleStyle({
                radius: 5,
                stroke: new Stroke({
                    color: 'rgba(0, 0, 0, 0.7)'
                }),
                fill: new Fill({
                    color: 'rgba(255, 255, 255, 0.2)'
                })
            })
        })
    })
}
addInteraction();

function pointerMoveHandler(evt) {
    if (evt.dragging) {
        return;
    }

    let helpMsg = '点击开始画图'
    if (sketch) {
        const geom = sketch.getGemetory();
        if (geom instanceof Polygon) {
            helpMsg = continuePolyginMsg
        } else {
            helpMsg = continueLineMsg
        }
    }

    helpTooltipElement.innerHTML = helpMsg
    helpTooltip.setPosition(evt.coordinate);

    helpTooltipElement.classlist.remove('hidden')
}

const map = new Map({
    layers: [raster, vector],
    target: 'map',
    view: new View({
        center: new fromLonLat([104, 30]),
        zoom: 10
    })
})
map.addInteraction(draw);
map.on('pontermove', pointerMoveHandler);
map.getViewport().addEventListener('mouseout', function() {
    helpTooltipElement.classlist.add('hidden');
});

const formatLength = (line) => {
    const length = getLength(line);
    let output;
    if (length > 100) {
        output = (Math.round(length / 1000 * 100)) + ' ' + 'km'
    } else {
        output = (Math.round(length * 100) / 100) + ' ' + 'km'
    }
    return output;
}

const formatArea = (polygon) => {
    const area = getArea(polygon);
    if (area > 10000) {
        output = (Math.round(area / 1000000 * 100) / 100) +
            ' ' + 'km<sup>2</sup>';
    } else {
        output = (Math.round(area * 100) / 100) +
            ' ' + 'm<sup>2</sup>';
    }
    return output;
}

let listener;
draw.on('drawstart', (evt) => {
    sketch = evt.sketch;
    const tooltipCoord = evt.coordinate;
    listener = sketch.getGeometry().on('change', (evt) => {
        const geom = evt.target;
        let output;
        if (geom instanceof Polygon) {
            output = formatArea(geom);
            tooltipCoord = geom.getInteriorPoint().getCoordinates();
        } else if (geom instanceof LineString) {
            output = formatLength(geom);
            tooltipCoord = geom.getLastCoordinate();
        }
        measureTooltipElement.innerHTML = output;
        measureTooltip.setPosition(tooltipCoord)
    })
})

draw.on('drawend', () => {
    measureTooltipElement.className = 'ol-tooltip ol-tooltip-static'
    measureTooltip.setOffset([0, -7]);
    scketch = null;
    measureTooltipElement = null;
    createMeasureTootip();
    unByKey(listener);
})

function createHelpTootip() {
    if (helpTooltipElement) {
        helpTooltipElement.parentNode.removeChild(helpTooltipElement);
    }
    helpTooltipElement = document.createElement('div');
    helpTooltipElement.className = 'ol-tooltip hidden';
    helpTooltip = new Overlay({
        element: helpTooltipElement,
        offset: [15, 10],
        position: 'center-left'
    });
    map.addOverlay(helpTooltip);
}

function createMeasureTootip() {
    if (measureTooltipElement) {
        measureTooltipElement.parentNode.removeChild(measureTooltipElement);
    }
    measureTooltipElement = document.createElement('div');
    measureTooltipElement.className = 'ol-tooltip ol-tooltip-measure';
    measureTooltip = new Overlay({
        element: measureTooltipElement,
        offset: [0, -15],
        position: 'bottom-center'
    })
    map.addOverlay(measureTooltip);
}
createMeasureTootip();
createHelpTootip();
//  切换工具时 重新添加交互
typeSleect.onchange = function() {
    map.removeInteraction(draw);
    addInteraction();
}